﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;
namespace TopUtility
{
    public class Utility
    {
        /// <summary>
        /// 获取应用的淘宝授权地址
        /// </summary>
        /// <param name="defaultUrl"></param>
        /// <param name="appKey"></param>
        /// <returns></returns>
        public static string GetSessionPostUrl(string defaultUrl, string appKey)
        {
            return defaultUrl + "?appkey=" + appKey;
        }

        /// <summary>
        /// 回调地址的验证
        /// </summary>
        /// <param name="topParams"></param>
        /// <param name="topSession"></param>
        /// <param name="topSign"></param>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static bool VerifyTopResponse(string topParams, string topSession, string topSign, string appKey, string appSecret)
        {
            StringBuilder result = new StringBuilder();
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            result.Append(appKey).Append(topParams).Append(topSession).Append(appSecret);
            byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(result.ToString()));
            string top = System.Convert.ToBase64String(bytes);
            return System.Convert.ToBase64String(bytes) == topSign;
        }
       
        /// <summary>
        /// 提示错误信息并跳转到错误页
        /// </summary>
        /// <param name="context"></param>
        /// <param name="errorMsg"></param>
        public static void GoError(HttpContext context,string errorMsg)
        {
            context.Response.Write("<script type=\"text/javascript\">alert('" + errorMsg + "');window.location.href='Error.aspx';</script>");
        }

        /// <summary>
        /// 提示错误信息 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="errorMsg"></param>
        public static void PrintError(HttpContext context, string errorMsg)
        {
            context.Response.Write("<script type=\"text/javascript\">alert('" + errorMsg + "');");
        }

        /// <summary>
        /// 获得一段js脚本
        /// </summary>
        /// <param name="script"></param>
        /// <returns></returns>
        public static string GetScript(string script)
        {
            return "<script type=\"text/javascript\">" + script + "</script>";
        }
    }
}
